﻿using IdentityModel;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wq.Core.Common;
using Wq.Core.Extensions.Assembly;
using Wq.Core.Model;

namespace Wq.Core.Extensions.ServiceExtensions
{
    public static class JwtSetup
    {
        public static void AddJwtSetup(this IServiceCollection services)
        {
            #region Jwt配置

            //添加身份验证
            services.AddAuthentication(options =>
            {
                //认证middleware配置
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                //jwt token参数设置
                o.TokenValidationParameters = new TokenValidationParameters
                {

                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Appsettings.app("JwtSettings:SecretKey"))),
                    // 验证秘钥
                    ValidateIssuerSigningKey = true,
                    // 验证发布者
                    ValidateIssuer = true,
                    // 验证Issure
                    ValidIssuer = Appsettings.app("JwtSettings:Issuer"),//发行人
                                                   // 验证接收者
                    ValidateAudience = true,
                    // 读配置Audience
                    ValidAudience = Appsettings.app("JwtSettings:Audience"),//订阅人
                                                       // 验证过期时间
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.FromSeconds(30),
                    RequireExpirationTime = true

                };
                o.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        // 如果过期，则把<是否过期>添加到，返回头信息中
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }

                        return Task.CompletedTask;
                    }
                };
            });
            #endregion

            services.AddAuthorization(options =>
            {
                options.AddPolicy("User", policy => policy.RequireRole("User").Build());
                options.AddPolicy("Manager", policy => policy.RequireRole("Manager"));

            });
        }
    }
}
